package com.gao.api.gate.quick.proto.http;

import com.gao.api.gate.quick.core.map.IgnoreCaseMultiValueMap;
import com.google.common.collect.ArrayListMultimap;
import io.netty.handler.codec.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import java.util.*;

/**
 * <p></p>
 *
 * @author gaoshuangwen
 * @since 2022/01/06 9:57
 */
public class Headers {

    private final IgnoreCaseMultiValueMap<String> headers;

    private Headers(HttpHeaders nettyHeaders){
        headers = new IgnoreCaseMultiValueMap<>(ArrayListMultimap.create());
        for (Map.Entry<String, String> nettyHeader : nettyHeaders) {
            String headerValue = nettyHeader.getValue();
            StringTokenizer st = new StringTokenizer(headerValue, ";");
            while (st.hasMoreTokens()) {
                headers.put(nettyHeader.getKey(),st.nextToken());
            }
        }
    }

    public void remove(String key) {
        headers.removeAll(key);
    }

    public void add(String key,String val){
        headers.put(key, val);
    }

    public List<String> get(String name) {
        return headers.get(name);
    }
    public String first(String name) {
        List<String> headerList = (List<String>) headers.get(name);
        if(headerList != null && headerList.size()>0){
            return headerList.get(0);
        }
        return null;
    }


    public static Headers build(HttpHeaders nettyHeaders){
        return new Headers(nettyHeaders);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Headers headers1 = (Headers) o;
        return Objects.equals(headers, headers1.headers);
    }

    @Override
    public int hashCode() {
        return Objects.hash(headers);
    }

}
